//
//  HomeViewController.swift
//  NetEasyNew
//
//  Created by 蔡万鸿 on 15/6/6.
//  Copyright (c) 2015年 黄花菜. All rights reserved.
//

import UIKit

class HomeViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate, ChannelLabelDelegate {
    
    @IBOutlet weak var channelView: UIScrollView!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var layout: UICollectionViewFlowLayout!
    //频道数组
    var channels: [Channel]?
    /**
    *  当前选中标签的索引
    */
    var currentIndex: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.channels = Channel.ChannelList()
        
        setupChannels()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        setupLayout()
    }
    
    func setupLayout() {
        self.layout.itemSize = self.collectionView.bounds.size;
        self.layout.minimumInteritemSpacing = 0;
        self.layout.minimumLineSpacing = 0;
        self.layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        self.collectionView.pagingEnabled = true;
        self.collectionView.showsHorizontalScrollIndicator = false;
    }
    
    // MARK: - 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.channels?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ChannelCell", forIndexPath: indexPath) as! ChannelCell
        
        var channel = self.channels![indexPath.item]
        
        cell.urlString = channel.urlString!

        return cell
    }
    
    //MARK: - ScrollView的代理方法
    
    // 只要滚动就执行
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var currentLabel = self.channelView.subviews[self.currentIndex] as! ChannelLabel
        var nextLabel:  ChannelLabel?
        
        var indexPaths = self.collectionView.indexPathsForVisibleItems()
        
        for path in indexPaths {
            if path.item != self.currentIndex {
                nextLabel = self.channelView.subviews[path.item] as? ChannelLabel
                break
            }
        }
        
        // 如果没有下一个标签，直接返回
        if nextLabel == nil {
            return
        }
        
        // 3. 知道变化了多少？
        var nextScale = abs(self.collectionView.contentOffset.x / self.collectionView.bounds.size.width - (CGFloat)(self.currentIndex))
        var currentScale = 1 - nextScale
        
        currentLabel.scale = (Double)(currentScale)
        nextLabel?.scale = (Double)(nextScale)

    }
    
    // 一旦停止，需要更新 currentIndex
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        self.currentIndex = (Int)(scrollView.contentOffset.x / scrollView.bounds.size.width)
    }
    
    func rndColor() -> CGFloat {
        return CGFloat(arc4random_uniform(256)) / 255
    }
    
    func setupChannels() {

        self.automaticallyAdjustsScrollViewInsets = false
        
        // 遍历频道数组，顺序添加标签
        let margin: CGFloat = 8.0;
        var x = margin;
        let h = self.channelView.bounds.size.height;
        
        var index = 0
        for channel in self.channels! {
            
            var l = ChannelLabel.channelLabelWithTitle(channel.tname!)
            
            l.frame = CGRectMake(x, 0, l.bounds.size.width, h)
            
            x += l.bounds.size.width + margin
            
            l.delegate = self
            l.tag = index
            
            index++
            self.channelView.addSubview(l)
        }
        
        // 设置 contentSize
        self.channelView.contentSize = CGSizeMake(x + margin, h)
        
        // 默认选中第0个标签
        self.currentIndex = 0;
        // 默认第0个标签的文字比例应该1
        var label = self.channelView.subviews[0] as! ChannelLabel
        label.scale = 1.0
    }
    
    func channelLabelDidSelected(channelLabel: ChannelLabel) {
        
        // 1. 记录当前的索引
        self.currentIndex = channelLabel.tag;
        
        // 2. 滚动 collectionView
        var indexPath =  NSIndexPath(forItem: self.currentIndex, inSection: 0)
        self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }

}
